<template>
  <div class="task-detail-page">
    <el-card>
      <div class="detail-header">
        <el-button @click="goBack" icon="el-icon-arrow-left" style="margin-bottom:20px">返回</el-button>
        <span style="font-size: 22px; font-weight: 600; margin-left:12px;">任务详情 - {{ task?.name || '' }}</span>
      </div>
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="8" animated />
      </div>
      <div v-else-if="task" class="task-details">
        <el-descriptions :column="2" border style="margin-bottom:20px;">
          <el-descriptions-item label="任务ID">{{ task.id }}</el-descriptions-item>
          <el-descriptions-item label="任务名称">{{ task.name }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(task.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ task.createdBy }}</el-descriptions-item>
          <el-descriptions-item label="总客户数">{{ task.customerCount }}</el-descriptions-item>
          <el-descriptions-item label="剩余客户数">{{ task.remainingCount }}</el-descriptions-item>
          <el-descriptions-item label="通道">{{ task.channel }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="task.status === 'completed' ? 'success' : (task.status === 'running' ? 'warning' : 'info')">
              {{ task.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <div class="task-customer-list">
          <h3>客户列表</h3>
          <el-table :data="customers" style="width: 100%" :row-style="{ height: '50px' }">
            <el-table-column prop="customer_name" label="客户姓名" width="120" />
            <el-table-column prop="phone" label="手机号" width="150" />
            <el-table-column prop="call_status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getCustomerStatusType(row.call_status)">
                  {{ getCustomerStatusText(row.call_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="call_time" label="拨打时间" width="180">
              <template #default="{ row }">{{ formatDate(row.call_time) }}</template>
            </el-table-column>
            <el-table-column prop="connected_time" label="接通时间" width="180">
              <template #default="{ row }">{{ formatDate(row.connected_time) }}</template>
            </el-table-column>
            <el-table-column prop="completed_time" label="完成时间" width="180">
              <template #default="{ row }">{{ formatDate(row.completed_time) }}</template>
            </el-table-column>
            <el-table-column prop="call_duration" label="通话时长/秒" width="180">
              <template #default="{ row }">{{ row.call_duration }}</template>
            </el-table-column>
            <el-table-column prop="call_result" label="结果" min-width="200" show-overflow-tooltip />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="openCustomerDetail(row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :page-size="pageSize"
              :current-page="page"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
      <div v-else class="empty-state"><el-empty description="未找到该任务" /></div>
    </el-card>

    <!-- 客户详情 -->
    <el-dialog v-model="customerDialogVisible" title="客户详情" width="720px">
      <div v-if="selectedCustomer">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户ID">{{ selectedCustomer.customer_id }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ selectedCustomer.customer_name }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ selectedCustomer.phone }}</el-descriptions-item>
          <el-descriptions-item label="城市">{{ selectedCustomer.city || '-' }}</el-descriptions-item>
          <el-descriptions-item label="来源">{{ selectedCustomer.source || '-' }}</el-descriptions-item>
          <el-descriptions-item label="类型">{{ selectedCustomer.type }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedCustomer.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(selectedCustomer.updated_at) }}</el-descriptions-item>
          <el-descriptions-item label="呼叫状态">
            <el-tag :type="getCustomerStatusType(selectedCustomer.call_status)">
              {{ getCustomerStatusText(selectedCustomer.call_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="拨打时间">{{ formatDate(selectedCustomer.call_time) }}</el-descriptions-item>
          <el-descriptions-item label="接通时间">{{ formatDate(selectedCustomer.connected_time) }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ formatDate(selectedCustomer.completed_time) }}</el-descriptions-item>
          <el-descriptions-item label="备注/结果" :span="2">{{ selectedCustomer.call_result || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="customerDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const id = route.params.id as string
const loading = ref(false)
const task = ref<any>(null)
const customers = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

// 客户详情弹窗
const customerDialogVisible = ref(false)
const selectedCustomer = ref<any | null>(null)

const fetchDetail = async () => {
  loading.value = true
  try {
    const resp = await axios.get(`/call/tasks/${id}/customers`, {
      params: { page: page.value, page_size: pageSize.value }
    })
    const body = resp.data?.data || resp.data
    customers.value = body.customers || []
    total.value = body.total || customers.value.length || 0
    if (body.task_info) {
      const t = body.task_info
      task.value = {
        id: t.id,
        name: t.task_name,
        customerCount: t.total_count,
        remainingCount: t.remaining_count,
        createdAt: t.created_at,
        createdBy: t.created_by,
        channel: t.channel,
        status: t.status,
        completedAt: t.completed_at || ''
      }
    }
  } catch (err) {
    ElMessage.error('获取任务详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(fetchDetail)
watchEffect(() => { fetchDetail() }, [page, pageSize])

const handleSizeChange = (size: number) => {
  pageSize.value = size
  page.value = 1
  fetchDetail()
}
const handlePageChange = (p: number) => {
  page.value = p
  fetchDetail()
}
const goBack = () => {
  router.back()
}

const openCustomerDetail = (row: any) => {
  selectedCustomer.value = row
  customerDialogVisible.value = true
}

// 引用原有的状态映射
const getCustomerStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'info'
    case 'dialing': return 'warning'
    case 'connected': return 'success'
    case 'ended': return 'info'
    case 'completed': return 'success'
    case 'failed': return 'danger'
    default: return 'info'
  }
}
const getCustomerStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待拨打',
    dialing: '拨打中',
    connected: '已接通',
    ended: '已结束',
    completed: '已完成',
    failed: '未接通/失败'
  }
  return map[status] || status || '未知'
}
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'
  })
}
</script>

<style scoped lang="scss">
.task-detail-page {
  padding: 32px 0;
  .detail-header {
    display: flex;
    align-items: center;
  }
  .loading-container {
    padding: 36px 0;
  }
  .task-details {
    margin-bottom: 24px;
  }
  .task-customer-list {
    margin-top: 16px;
    h3 {
      font-size: 18px;
      margin-bottom: 12px;
    }
  }
  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
